/**
 * 
 */
package com.cipe.cmrs.controllers;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cipe.cmrs.model.Country;
import com.cipe.cmrs.model.State;
import com.cipe.cmrs.service.CountryService;
import com.cipe.cmrs.service.RegionService;
import com.cipe.cmrs.service.UserService;

/**
 * @author Incepio
 *
 */
@Controller
public class CountryController extends BaseController {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= -3823562098119817733L;
	@Autowired
	private CountryService		countryService;
	@Autowired
	private RegionService		regionService;
	@Autowired
	private UserService					userService;
	
	@RequestMapping("/secure/saveCountry.do")
	public String SaveCountry(@ModelAttribute("country") Country country, BindingResult result, Model model, HttpServletRequest request) {
		try {
			country = countryService.saveCountry(country, getUserId(request));
			saveMessage(request, getText("editCountry.message.success"));
		} catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}
		model.addAttribute("country", country);
		model.addAttribute("users", userService.findAll());
		model.addAttribute("regionList", regionService.findAll());
		return "editCountry";
	}

	@RequestMapping("/secure/showAddCountry.do")
	public String showAddCountry(Model model) {
		model.addAttribute("country", new Country());
		model.addAttribute("regionList", regionService.findAll());
		model.addAttribute("users", userService.findAll());
		return "editCountry";
	}

	@RequestMapping("/secure/showCountryList.do")
	public String showCountryList(Model model) {
		model.addAttribute("countrys", countryService.findAll());
		return "countryList";
	}

	@RequestMapping("/secure/showEditCountry.do")
	public String showEditCountry(@RequestParam Integer id, Model model) {
		model.addAttribute("country", countryService.findById(id));
		model.addAttribute("regionList", regionService.findAll());
		model.addAttribute("users", userService.findAll());
		return "editCountry";
	}
	
	@RequestMapping(value="/secure/loadStates.do", method=RequestMethod.GET) 
	public @ResponseBody Map<String,String> loadStatesViaAjax(@RequestParam Integer countryId, Model model) {
		Map<String, String> results = null;
		Country country = countryService.findById(countryId);
		
		if(country != null) { 
			List<State> states = country.getStates();
			results = new HashMap<String, String>();
			/* Note: we could let Spring serialize the list of states automatically, but
			 	  for this list it reports an error.. the bidirectional mapping between country & state
			 	  in the underlying beans confuse the jackson's serializer... so it is done manually
			 */
			if(states != null && !states.isEmpty()) {
				for(State state : states) { 
					// TODO: this actually acts like a LIFO in the front end, try to sort them first... 
					results.put(state.getId().toString(), state.getDisplayName());
				}
			}
		}
		
		return results;
	}	
	
	@RequestMapping(value="/secure/loadCountryUsers.do", method=RequestMethod.GET) 
	public @ResponseBody Map<String,String> loadCountryUsersViaAjax(@RequestParam Integer countryId, Model model) {
		Map<String, String> results = new LinkedHashMap<String, String>();
		Country country = countryService.findById(countryId);
		
		if(country != null) { 
			results.put("programOfficer", country.getProgramOfficer() != null ? 
					String.valueOf(country.getProgramOfficer().getId()) : "");
			results.put("programAssistant", country.getProgramAssistant() != null ? 
					String.valueOf(country.getProgramAssistant().getId()) : "");			
		}
		
		return results;
	}	
	
}
